package com.bytecodezz.app.learn2;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLSurfaceView;
import android.util.AttributeSet;

import java.nio.ByteBuffer;

import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;

public class TextureGLSurfaceView extends GLSurfaceView {
    private InnerRenderer mGLRender;
    private NativeRenderer mNativeRenderer;

    public TextureGLSurfaceView(Context context) {
        super(context);
    }

    public TextureGLSurfaceView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setEGLContextClientVersion(3);
        mNativeRenderer = new NativeRenderer();
        mGLRender = new InnerRenderer(mNativeRenderer);
        setEGLContextClientVersion(3);
        setRenderer(mGLRender);
        setRenderMode(RENDERMODE_CONTINUOUSLY);
 }


    public class InnerRenderer implements GLSurfaceView.Renderer {
        private NativeRenderer mNativeRenderer;
        private long nativePtr;

        public void setImageData(int format, int width, int height, byte[] data) {
            mNativeRenderer.nativeInsertImageData(nativePtr, format, width, height, data);
        }

        public InnerRenderer(NativeRenderer mNativeRenderer) {
            this.mNativeRenderer = mNativeRenderer;
        }

        @Override
        public void onSurfaceCreated(GL10 gl, EGLConfig config) {
            nativePtr = mNativeRenderer.nativeInitRenderer();
            //设置图片
            Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.texture_img);
            int bytes = bitmap.getByteCount();
            ByteBuffer buffer = ByteBuffer.allocate(bytes);
            bitmap.copyPixelsToBuffer(buffer);
            byte[] data = buffer.array();
            mGLRender.setImageData(bitmap.getConfig().ordinal(), bitmap.getWidth(), bitmap.getHeight(), data);

        }

        @Override
        public void onSurfaceChanged(GL10 gl, int width, int height) {
            mNativeRenderer.nativeSurfaceChange(nativePtr, width, height);
        }

        @Override
        public void onDrawFrame(GL10 gl) {
            mNativeRenderer.nativeDraw(nativePtr);

        }
    }

}
